interface ApiResponse<T = any> {
  code: number
  data: T
  message: string
}

/**
 * 错误处理器类（责任链模式）
 */
class ErrorHandler {
  private nextHandler?: ErrorHandler

  setNext(handler: ErrorHandler): ErrorHandler {
    this.nextHandler = handler
    return handler
  }

  handle(status: number, error: any): void {
    if (this.nextHandler) {
      this.nextHandler.handle(status, error)
    } else {
      window['$message']?.error(error.message || '未知错误')
    }
  }
}

class BadRequestHandler extends ErrorHandler {
  handle(status: number, error: any): void {
    if (status === 400) {
      window['$message']?.warning(error.message || '请求参数错误')
    } else {
      super.handle(status, error)
    }
  }
}

class UnauthorizedHandler extends ErrorHandler {
  handle(status: number, error: any): void {
    if (status === 401) {
      window['$message']?.error('未授权，请重新登录')
    } else {
      super.handle(status, error)
    }
  }
}

class ForbiddenHandler extends ErrorHandler {
  handle(status: number, error: any): void {
    if (status === 403) {
      window['$message']?.error('禁止访问')
    } else {
      super.handle(status, error)
    }
  }
}

class ServerErrorHandler extends ErrorHandler {
  handle(status: number, error: any): void {
    if (status >= 500 && status < 600) {
      window['$message']?.error('服务器内部错误，请稍后重试')
    } else {
      super.handle(status, error)
    }
  }
}

// 初始化错误处理链
const errorHandlerChain = new BadRequestHandler()
errorHandlerChain.setNext(new UnauthorizedHandler()).setNext(new ForbiddenHandler()).setNext(new ServerErrorHandler())

export const setupResponseInterceptor = (axiosInstance: any) => {
  axiosInstance.interceptors.response.use(
    (response: { data: ApiResponse }) => {
      const res = response.data
      if (res.code === 200) {
        return res.data
      }
      // 处理业务错误
      const error = new Error(res.message || '请求失败')
      errorHandlerChain.handle(res.code, error)
      throw error
    },
    (error: any) => {
      // 处理 HTTP 错误
      if (error.response) {
        errorHandlerChain.handle(error.response.status, error)
      } else {
        window['$message']?.error('网络错误，请检查网络连接')
      }
      return Promise.reject(error)
    }
  )
}
